from flask import Blueprint, render_template, redirect, url_for, flash, request
from flask_login import login_required
from sqlalchemy.orm import joinedload

from app import db
from app.models.order import Order, OrderItem
from app.models.blind_box import BlindBox
from app.models.supermarket import Supermarket
from app.models.user import User
from app.utils.tracking import track_user_behavior

order = Blueprint('order', __name__, url_prefix='/order')

@order.route('/list')
@login_required
def list():
    """订单列表"""
    # 获取筛选参数
    status = request.args.get('status')
    user_id = request.args.get('user_id')
    order_no = request.args.get('order_no')
    username = request.args.get('username')
    
    query = Order.query
    
    # 应用筛选条件
    if status:
        query = query.filter(Order.status == int(status))
    if user_id:
        query = query.filter(Order.user_id == int(user_id))
    if order_no:
        query = query.filter(Order.order_no.like(f'%{order_no}%'))
    if username:
        # 根据用户名筛选，需要先查找匹配的用户ID
        user_ids = db.session.query(User.user_id).filter(User.username.like(f'%{username}%')).all()
        user_ids = [user_id[0] for user_id in user_ids]
        if user_ids:
            query = query.filter(Order.user_id.in_(user_ids))
        else:
            # 如果没有找到匹配的用户，返回空结果
            query = query.filter(Order.user_id == -1)  # 使用不存在的用户ID
    
    # 获取所有订单
    orders = query.order_by(Order.create_time.desc()).all()
    
    # 获取所有用户
    users = User.query.all()
    
    return render_template('order/list.html', 
                         orders=orders, 
                         users=users)

@order.route('/detail/<int:order_id>')
@login_required
def detail(order_id):
    """订单详情"""
    # 查询订单信息，并预加载相关数据
    order = Order.query.options(
        joinedload(Order.user),
        joinedload(Order.supermarket)
    ).get_or_404(order_id)
    
    # 查询订单明细，并预加载盲盒信息
    order_items = OrderItem.query.options(
        joinedload(OrderItem.blind_box)
    ).filter_by(order_id=order_id).all()
    
    # 这里确保传递的变量名为 order_items
    return render_template('order/detail.html', 
                          order=order, 
                          order_items=order_items)  # 注意变量名必须为 order_items

@order.route('/update_status/<int:order_id>/<int:status>')
@login_required
def update_status(order_id, status):
    """更新订单状态"""
    order = Order.query.get_or_404(order_id)
    
    if status not in [0, 1, 2, 3, 4]:
        flash('无效的订单状态!', 'danger')
        return redirect(url_for('order.detail', order_id=order_id))
    
    # 更新状态
    order.status = status
    db.session.commit()
    
    # 如果订单完成，记录purchase行为
    if status == 3:
        # 获取订单明细
        order_items = OrderItem.query.filter_by(order_id=order_id).all()
        for item in order_items:
            track_user_behavior('purchase', item.box_id, 'box')
    
    status_text = {0: '待支付', 1: '已支付', 2: '已发货', 3: '已完成', 4: '已取消'}
    flash(f'订单状态已更新为: {status_text[status]}!', 'success')
    return redirect(url_for('order.detail', order_id=order_id))

@order.route('/delete/<int:order_id>')
@login_required
def delete(order_id):
    """删除订单"""
    order = Order.query.get_or_404(order_id)
    
    db.session.delete(order)
    db.session.commit()
    
    flash('订单已删除!', 'success')
    return redirect(url_for('order.list')) 